package com.yanqu.road.server.cmd;

import com.yanqu.road.connect.AgentServerLinkControl;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.server.ServerProto;
import com.yanqu.road.player.Player;
import com.yanqu.road.player.PlayerControl;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Cmd(code = Protocol.A_GAME_TRANSFER, desc = "区服消息转发")
public class GameAgentTransferCmd implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage packet) throws Exception {

        ServerProto.GameAgentTransferMsg agentTransferMsg = ServerProto.GameAgentTransferMsg.parseFrom(packet.getBytes());
        int code = agentTransferMsg.getCode();
        List<Long> userIdList = agentTransferMsg.getUserIdList();
        boolean syncOffLineUser = agentTransferMsg.getSyncOffLineUser();
        byte[] msgBytes = agentTransferMsg.getMsg().toByteArray();

        Map<Long, Player> allPlayer = new HashMap<>(PlayerControl.getOnlinePlayerMap());
        if (userIdList.isEmpty()) {//为空表示转发给所有在线玩家
            userIdList = new ArrayList<>(allPlayer.keySet());
        }

        for (long userId : userIdList) {
            if (!syncOffLineUser && !allPlayer.containsKey(userId)) {
                continue;
            }
            YanQuMessage message = YanQuMessageUtils.buildMessageByte(code, msgBytes);
            message.setPlayerId(userId);
            message.setLen(packet.getLen());
            // 有其他转发处理的再加
            if (code > 20000 && code < 30000) {
                // 转到游戏服去处理
                AgentServerLinkControl.routeGame(message);
            } else {
                AgentServerLinkControl.routeClient(message);
            }
        }

    }
}
